package com.koro.service.impl;

import com.koro.dto.FindGoodsDTO;
import com.koro.dto.FindUsersDTO;
import com.koro.dto.SaveGoodsDTO;
import com.koro.dto.SaveOrdersDTO;
import com.koro.feign.GoodsFeignClient;
import com.koro.feign.OrderFeignClient;
import com.koro.feign.UsersFeigunClient;
import com.koro.service.OrdersService;
import com.koro.vo.FindGoodsVO;
import com.koro.vo.FindUsersVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Random;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private GoodsFeignClient goodsFeignClient;
    @Autowired
    private UsersFeigunClient usersFeigunClient;
    @Autowired
    private OrderFeignClient orderFeignClient;

    @Override
    public Integer subOrders(SaveOrdersDTO dto) {
        // 查询商品信息
        FindGoodsDTO findGoodsDTO = new FindGoodsDTO();
        findGoodsDTO.setId(dto.getGoodsId());
        FindGoodsVO goodsVO = goodsFeignClient.findById(findGoodsDTO).getData();
        // 查询用户信息
        FindUsersDTO findUsersDTO = new FindUsersDTO();
        findUsersDTO.setId(dto.getUserId());
        FindUsersVO usersVO = usersFeigunClient.findById(findUsersDTO).getData();
        // 下单操作
        int nextInt = new Random(10000).nextInt();
        dto.setOrderNo(String.valueOf(nextInt));
        dto.setGoodsName(goodsVO.getGoodsName());
        dto.setUsername(usersVO.getUsername());
        dto.setTotalPrice(goodsVO.getPrice().multiply(new BigDecimal(dto.getNum())));
        // 下单成功商品扣减库存
        SaveGoodsDTO saveGoodsDTO = new SaveGoodsDTO();
        BeanUtils.copyProperties(goodsVO,saveGoodsDTO);
        saveGoodsDTO.setStock(goodsVO.getStock() - dto.getNum());
        goodsFeignClient.save(saveGoodsDTO);
        return orderFeignClient.save(dto).getData();
    }
}
